package week8;

import java.util.*;

/**
 * 
 * Practicumopgave Programmeren 1
 * @author Rick Clement en Adriaan Dekker
 * @version $Revision: 1.3 $
 */
public class SlimmeStrategie implements Strategie {
    // ------------------ Instantievariabelen ----------------
	private final String naam = "Slimme";
   
    // ------------------ Aanvragen --------------------------

    /**
     * Levert naam van deze Strategie op.
     */
	public String getNaam(){
		return naam;
	}

    /**
     * Bepaalt de zet.		// Orly?
     */
	public int bepaalZet(Bord b, Mark m) {
		int result = (b.DIM * b.DIM) / 2;
		int zelfWin = winIx(b, m);
		int tegenWin = winIx(b, m.other());
		if (b.isLeegVakje(result)) {
		} else if(zelfWin != -1) {
			result = zelfWin;
		} else if(tegenWin != -1) {
			result = tegenWin;
		} else {
			List<Integer> markList = new ArrayList<Integer>();
			for(int i = 0; i < b.DIM * b.DIM; i++){
				if(b.isLeegVakje(i)){
					markList.add(i);
				}
			}
			int randomIx = (int)(Math.random() * markList.size());
			result = markList.get(randomIx);
		}
		return result;
	}
	
	private int winIx(Bord b, Mark m){
		Bord checkBord = b.deepCopy();
		int winIndex = -1;
		for(int i = 0; i < b.DIM*b.DIM; i++){
			if(b.isLeegVakje(i)){
				b.setVakje(i, m);
				if(b.isWinnaar(m)){
					winIndex = i;
				}
				b.setVakje(i, Mark.LEEG);
			}
		}
		return winIndex;
	}
}